package com.my12306.user.service.auth.impl;

import com.my12306.user.model.po.PUserEntity;
import com.my12306.user.service.PUserService;
import com.my12306.user.service.auth.PermissionService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author:苏牧夕
 * @Date:2020/5/21 1:09
 * @Version 1.0
 */
@Service("myPhoneDetailService")
public class MyPhoneDetailService implements UserDetailsService {
    @Autowired
    private PUserService pUserService;
    @Autowired
    private PermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        PUserEntity user = pUserService.queryUserByPhone(phone);
        if (user == null) return null;
        List<String> permissionList = permissionService.getUserPermissionByUser_id(user.getId());

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        System.out.println(6666);
//        System.out.println(permissionList);
        permissionList.stream().filter(x -> StringUtils.isNotEmpty(x)).forEach(ps -> {
            List<String> split = Arrays.asList(ps.split(","));
            split.stream().forEach(sp -> {
                grantedAuthorities.add(new SimpleGrantedAuthority(sp));
            });
        });
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setCredentialsNonExpired(true);
        user.setEnabled(true);

//        System.out.println("6666666666");
        user.setAuthorities(grantedAuthorities);
//        System.out.println(user);
        return user;
    }
}
